package nl.hanze.designpatterns.mvc.view;

import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

import nl.hanze.designpatterns.mvc.controller.LoginController;

public class LoginView extends View{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private LoginController loginController;
	private SpringLayout layout;
	private JLabel userLabel;
	private JLabel passwordLabel; 
	private JTextField username;
	private JPasswordField password;
	private JButton loginButton;
	
	
	public LoginView(LoginController loginController){
		this.init(loginController);
		this.addPanels();
		this.locateItems();
	}
	
	
	private void init(LoginController loginController){
		this.loginController = loginController;
		this.layout = new SpringLayout();
		this.setLayout(layout);
		
		this.username = new JTextField(15);
		this.password = new JPasswordField(15);
		
		this.userLabel = new JLabel("Username: ");
		this.passwordLabel = new JLabel("Password: ");
		
		this.loginButton = new JButton("login");
		this.loginButton.setActionCommand("login");
		this.loginButton.addActionListener(this);
	}
	
	private void addPanels(){
		super.add(userLabel);
		super.add(username);
		super.add(passwordLabel);
		super.add(password);
		super.add(loginButton);		
	}
	
	private void locateItems(){
		//userLabel position
		this.layout.putConstraint(SpringLayout.WEST, userLabel, 30, SpringLayout.WEST, this);
		this.layout.putConstraint(SpringLayout.NORTH, userLabel, 50, SpringLayout.NORTH, this);
		//username position
		this.layout.putConstraint(SpringLayout.WEST, username, 100, SpringLayout.WEST, this);
		this.layout.putConstraint(SpringLayout.NORTH, username, 50, SpringLayout.NORTH, this);
		//passwordLabel position
		this.layout.putConstraint(SpringLayout.WEST, passwordLabel, 30, SpringLayout.WEST, this);
		this.layout.putConstraint(SpringLayout.NORTH, passwordLabel, 80, SpringLayout.NORTH, this);
		//password position
		this.layout.putConstraint(SpringLayout.WEST, password, 100, SpringLayout.WEST, this);
		this.layout.putConstraint(SpringLayout.NORTH, password, 80, SpringLayout.NORTH, this);
		//loginButton position
		this.layout.putConstraint(SpringLayout.WEST, loginButton, 208, SpringLayout.WEST, this);
		this.layout.putConstraint(SpringLayout.NORTH, loginButton, 110, SpringLayout.NORTH, this);
	}
	
	

	@Override
	public void actionPerformed(ActionEvent e) {
		System.out.println(e.getActionCommand());
		try{
			switch(e.getActionCommand()){
			case "login":
				this.loginController.handleLoginRequest(this.username.getText(), this.password.getPassword());
				break;
			default:
				throw new Exception("Unknown Command");
			}
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		
		System.out.println("werkt");
		
	}
}
